import zqdb.script as zqdb

class OrderClose(zqdb.Script):
    """"""

    # 这里是默认设置，其中input是用户可以通过设置界面修改的入参
    default_setting = {
        'type':'',
        'name':'快平',
        'desc':'快速平仓。',
        'input':{
            "order_type": zqdb.ORDER_TYPE.MARKET,
            "price": 0.0,
            "volume": 0.0
        }
    }

    # 构造函数，外部需要传入setting设置，用户可以在构造函数里关联计算数据/指标等
    def __init__(
        self,
        setting: dict
    ):
        """Constructor"""
        super().__init__(setting)
        input = setting["input"]
        self.order_type = input["order_type"]
        self.price = input["price"]
        self.volume = input["volume"]

    # 计算函数，当关联的计算数据/指标等更新时就会被调用，脚本可以调用交易相关函数
    def on_calc(self, code):
        """"""
        # 脚本算法请在这里编写...
        
        user = self.user
        if not user:
            zqdb.LogInfo("快速平仓失败，交易账号为空")
            return

        close = False
        position = zqdb.Position(user, code, zqdb.DIRECTION_TYPE.LONG)
        if position:
            volume = volume = self.volume if self.volume > 0 else self.order_default_volume(code)
            avail_volume = position.Volume - position.FrozenVolume
            if volume <= 0 or volume > avail_volume:
                 volume = avail_volume
            if volume > 0:
                close = True
                orderid = self.order_close(position, self.order_type, self.price, volume)
                zqdb.LogInfo("快速平仓委托成功" if len(orderid) > 0 else "快速平仓委托失败", orderid, "代码=", code.Code, " 类型=", self.order_type, " 价格=", self.price, " 量=", volume)

        position = zqdb.Position(user, code, zqdb.DIRECTION_TYPE.SHORT)
        if position:
            volume = volume = self.volume if self.volume > 0 else self.order_default_volume(code)
            avail_volume = position.Volume - position.FrozenVolume
            if volume <= 0 or volume > avail_volume:
                 volume = avail_volume
            if volume > 0:
                close = True
                orderid = self.order_close(position, self.order_type, self.price, volume)
                zqdb.LogInfo("快速平仓委托成功" if len(orderid) > 0 else "快速平仓委托失败", orderid, "代码=", code.Code, " 类型=", self.order_type, " 价格=", self.price, " 量=", volume)

        if not close:
            zqdb.LogInfo("没有可平持仓")
        
        pass

